import 'package:flutter/material.dart';

/// 新建项目的弹窗对话框
class NewProjectDialog extends StatefulWidget {
  const NewProjectDialog({super.key});

  @override
  State<NewProjectDialog> createState() => _NewProjectDialogState();
}

class _NewProjectDialogState extends State<NewProjectDialog> {
  /// 表单校验 key
  final _formKey = GlobalKey<FormState>();

  /// 输入框控制器：项目名称
  final _nameCtrl = TextEditingController(text: '');

  /// 输入框控制器：项目位置
  final _locationCtrl = TextEditingController(text: '');

  /// 输入框控制器：包名/分组（默认 com.example）
  final _groupCtrl = TextEditingController(text: 'com.example');

  /// 构建系统，默认使用 Snow Modules
  String _buildSystem = 'Snow Modules';

  /// 是否包含示例代码（固定为 true，不可修改）
  final bool _withSample = true;

  /// Web 平台下的目录句柄（仅 Web 有效，桌面端/移动端为 null）
  Object? _webDirectoryHandle;

  @override
  void dispose() {
    _nameCtrl.dispose();
    _locationCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    const gap = SizedBox(height: 12); // 公共间隔控件

    return AlertDialog(
      title: const Text('New Project'),
      content: ConstrainedBox(
        constraints: const BoxConstraints(
          minWidth: 500,
          minHeight: 300,
          maxWidth: 600,
        ),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              /// 项目名称输入框
              TextFormField(
                controller: _nameCtrl,
                decoration: const InputDecoration(labelText: 'Name'),
                validator: (v) =>
                (v == null || v.trim().isEmpty) ? 'Please enter a name' : null,
              ),
              gap,

              /// 构建系统选择
              DropdownButtonFormField<String>(
                value: _buildSystem,
                decoration: const InputDecoration(labelText: 'Build system'),
                items: const [
                  DropdownMenuItem(
                    value: 'Snow Modules',
                    child: Text('Snow Modules'),
                  ),
                ],
                onChanged: (v) => setState(() => _buildSystem = v ?? _buildSystem),
              ),
              gap,

              /// Group（包名）输入框
              TextFormField(
                controller: _groupCtrl,
                decoration: const InputDecoration(labelText: 'Group'),
                validator: (v) =>
                (v == null || v.trim().isEmpty) ? 'Please enter Group' : null,
              ),
              gap,

              /// 示例代码选项（固定为启用状态，不可取消）
              Align(
                alignment: Alignment.centerLeft,
                child: CheckboxListTile(
                  contentPadding: EdgeInsets.zero,
                  controlAffinity: ListTileControlAffinity.leading,
                  title: const Text('Add example code'),
                  value: _withSample,
                  onChanged: null, // 禁止手动修改
                ),
              ),
            ],
          ),
        ),
      ),

      /// 底部操作按钮
      actions: [
        /// 取消按钮：关闭对话框
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('Cancel'),
        ),

        /// 确认按钮：校验表单并返回输入结果
        FilledButton(
          onPressed: () {
            if (_formKey.currentState?.validate() ?? false) {
              Navigator.of(context).pop(
                NewProjectData(
                  name: _nameCtrl.text.trim(),
                  location: _locationCtrl.text.trim().isEmpty
                      ? null
                      : _locationCtrl.text.trim(),
                  buildSystem: _buildSystem,
                  withSample: _withSample,
                  webDirectoryHandle: _webDirectoryHandle,
                  group: _groupCtrl.text.trim(),
                ),
              );
            }
          },
          child: const Text('Create'),
        ),
      ],
    );
  }
}

/// 新建项目时收集到的数据
class NewProjectData {
  NewProjectData({
    required this.name,
    required this.buildSystem,
    required this.withSample,
    required this.group,
    this.location,
    this.webDirectoryHandle,
  });

  final String name; // 项目名称
  final String? location; // 项目路径（可选）
  final String buildSystem; // 构建系统
  final String group; // 包名/分组
  final bool withSample; // 是否包含示例代码

  /// Web 平台专用：FileSystemDirectoryHandle（JS 对象）
  final Object? webDirectoryHandle;
}
